package com.bs.bsacexj.service.impl;

import com.alibaba.fastjson2.TypeReference;
import com.bs.bsacexj.common.StringUtils;
import com.bs.bsacexj.domain.AccessControlDeviceInfoVO;
import com.bs.bsacexj.domain.AccessControlEventInfoVO;
import com.bs.bsacexj.service.IAccessControlManageService;

import java.util.*;

import com.hikvision.artemis.sdk.ArtemisHttpUtil;
import com.hikvision.artemis.sdk.config.ArtemisConfig;
import org.springframework.beans.factory.annotation.Value;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.stereotype.Service;

@Service
public class HIKSafePlatACEService implements IAccessControlManageService {
    /**
     * API网关的后端服务上下文为：/artemis
     */
    private static final String ARTEMIS_PATH = "/artemis";

    @Value("${third-party.hikvision.host}")
    String host;

    @Value("${third-party.hikvision.appkey}")
    String appKey;

    @Value("${third-party.hikvision.appSecret}")
    String appSecret;

    @Value("${third-party.hikvision.tagId}")
    String tagId;


    @Override
    public List<AccessControlEventInfoVO> selectAccessControlEventList(String startTime, String endTime, int pageIndex, int pageSize) throws Exception {
        ArtemisConfig config = new ArtemisConfig();
        config.setHost(host); // 代理API网关nginx服务器ip端口
        config.setAppKey(appKey);  // 秘钥appkey
        config.setAppSecret(appSecret);// 秘钥appSecret
        final String getCamsApi = ARTEMIS_PATH + "/api/acs/v1/door/events";
        Map<String, Object> paramMap = new HashMap<String, Object>();// post请求Form表单参数
        paramMap.put("startTime", startTime);
        paramMap.put("endTime", endTime);
        paramMap.put("pageNo", pageIndex);
        paramMap.put("pageSize", pageSize);
        String body = JSON.toJSON(paramMap).toString();
        Map<String, String> path = new HashMap<String, String>(2) {
            {
                put("https://", getCamsApi);
            }
        };
        String resultDataString= ArtemisHttpUtil.doPostStringArtemis(config,path, body, null, null, "application/json");
        JSONObject resultObject = JSON.parseObject(resultDataString);
        JSONObject devicesObject=(JSONObject) resultObject.get("data");
        String eventsString=String.valueOf(devicesObject.get("list"));
//        List<AccessControlEventInfoVO> eventsList=JSONObject.parseArray(eventsString,AccessControlEventInfoVO.class);
        List<AccessControlEventInfoVO> eventsList=JSON.parseObject(eventsString, new TypeReference<List<AccessControlEventInfoVO>>(){});
        return eventsList;
    }

    @Override
    public List<AccessControlDeviceInfoVO> selectAccessControlDeviceList(int pageIndex, int pageSize) throws Exception {
        ArtemisConfig config = new ArtemisConfig();
        config.setHost(host); // 代理API网关nginx服务器ip端口
        config.setAppKey(appKey);  // 秘钥appkey
        config.setAppSecret(appSecret);// 秘钥appSecret
        final String getCamsApi = ARTEMIS_PATH + "/api/resource/v1/acsDoor/advance/acsDoorList";
        Map<String, Object> paramMap = new HashMap<String, Object>();// post请求Form表单参数
        paramMap.put("pageNo", pageIndex);
        paramMap.put("pageSize", pageSize);
        String body = JSON.toJSON(paramMap).toString();
        Map<String, String> path = new HashMap<String, String>(2) {
            {
                put("https://", getCamsApi);
            }
        };
        String resultDataString= ArtemisHttpUtil.doPostStringArtemis(config,path, body, null, null, "application/json");
        JSONObject resultObject = JSON.parseObject(resultDataString);
        JSONObject devicesObject=(JSONObject) resultObject.get("data");
        String devicesString=String.valueOf(devicesObject.get("list"));
        List<AccessControlDeviceInfoVO> deviceInfoVOList=JSON.parseObject(devicesString, new TypeReference<List<AccessControlDeviceInfoVO>>(){});
        return deviceInfoVOList;
    }

    //根据用户的身份证号查询用户信息
    public String selectUserInfo(String cardNO) throws Exception {
        /**
         * https://ip:port/artemis/api/resource/v1/org/orgList
         * 通过查阅AI Cloud开放平台文档或网关门户的文档可以看到获取组织列表的接口定义,该接口为POST请求的Rest接口, 入参为JSON字符串，接口协议为https。
         * ArtemisHttpUtil工具类提供了doPostStringArtemis调用POST请求的方法，入参可传JSON字符串, 请阅读开发指南了解方法入参，没有的参数可传null
         */
        ArtemisConfig config = new ArtemisConfig();
        config.setHost(host); // 代理API网关nginx服务器ip端口
        config.setAppKey(appKey);  // 秘钥appkey
        config.setAppSecret(appSecret);// 秘钥appSecret
        final String getCamsApi = ARTEMIS_PATH + "/api/resource/v1/person/certificateNo/personInfo";
        Map<String, Object> paramMap = new HashMap<String, Object>();// post请求Form表单参数
        paramMap.put("certificateNo", cardNO);
        paramMap.put("certificateType", 111);
        String body = JSON.toJSON(paramMap).toString();
        Map<String, String> path = new HashMap<String, String>(2) {
            {
                put("https://", getCamsApi);
            }
        };
        String resultDataString= ArtemisHttpUtil.doPostStringArtemis(config,path, body, null, null, "application/json");
        JSONObject resultObject = JSON.parseObject(resultDataString);
        JSONObject userInfoObject=(JSONObject) resultObject.get("data");
        return userInfoObject.get("personId").toString();
    }

    //执行权限配置
    public boolean configurationShortcut(String deviceId) throws Exception {
        ArtemisConfig config = new ArtemisConfig();
        config.setHost(host); // 代理API网关nginx服务器ip端口
        config.setAppKey(appKey);  // 秘钥appkey
        config.setAppSecret(appSecret);// 秘钥appSecret
        final String getCamsApi = ARTEMIS_PATH + "/api/acps/v1/authDownload/configuration/shortcut";
        Map<String, Object> paramMap = new HashMap<String, Object>();// post请求Form表单参数
        paramMap.put("taskType", 1);
        List<Object> resourceInfosList=new ArrayList<>();
        JSONObject resourceInfo=new JSONObject();
        resourceInfo.put("resourceIndexCode",deviceId);
        resourceInfo.put("resourceType","door");
        resourceInfosList.add(resourceInfo);
        paramMap.put("resourceInfos", resourceInfosList);
        String body = JSON.toJSON(paramMap).toString();
        Map<String, String> path = new HashMap<String, String>(2) {
            {
                put("https://", getCamsApi);
            }
        };
        String resultDataString= ArtemisHttpUtil.doPostStringArtemis(config,path, body, null, null, "application/json");
        JSONObject resultObject = JSON.parseObject(resultDataString);
        JSONObject devicesObject=(JSONObject) resultObject.get("data");
        String taskIdString=String.valueOf(devicesObject.get("taskId"));
        boolean result=false;
        if(StringUtils.isNotEmpty(taskIdString)){
            result=true;
        }
        return result;

    }

    //删除权限配置
    public boolean deleteAuthConfig(String personId, String deviceId) throws Exception {
        ArtemisConfig config = new ArtemisConfig();
        config.setHost(host); // 代理API网关nginx服务器ip端口
        config.setAppKey(appKey);  // 秘钥appkey
        config.setAppSecret(appSecret);// 秘钥appSecret
        final String getCamsApi = ARTEMIS_PATH + "/api/acps/v1/auth_config/delete";
        Map<String, Object> paramMap = new HashMap<String, Object>();// post请求Form表单参数

        //配置权限下发参数
        JSONObject personParmJson=new JSONObject();
        List<Object> personIds=new ArrayList<>();
        List<Object> personDatas=new ArrayList<>();
        personIds.add(personId);
        personParmJson.put("indexCodes",personIds);
        personParmJson.put("personDataType","person");
        personDatas.add(personParmJson);
        paramMap.put("personDatas",personDatas);
        //拼接门禁设备参数
        JSONObject resourceInfosParmJson=new JSONObject();
        resourceInfosParmJson.put("resourceIndexCode",deviceId);
        resourceInfosParmJson.put("resourceType","door");
        List<Object> resourceIds=new ArrayList<>();
        resourceIds.add(resourceInfosParmJson);
        paramMap.put("resourceInfos",resourceIds);
        String body = JSON.toJSON(paramMap).toString();
        Map<String, String> path = new HashMap<String, String>(2) {
            {
                put("https://", getCamsApi);
            }
        };
        Map<String, String> head = new HashMap<String, String>(2) {
            {
                put("tagId", tagId);
            }
        };
        String resultDataString= ArtemisHttpUtil.doPostStringArtemis(config,path, body, null, null, "application/json",head);
        JSONObject resultObject = JSON.parseObject(resultDataString);
        JSONObject devicesObject=(JSONObject) resultObject.get("data");
        String taskIdString=String.valueOf(devicesObject.get("taskId"));
        boolean result=false;
        if(StringUtils.isNotEmpty(taskIdString)){
            result=true;
        }
        return result;
    }

    //添加权限配置
    public boolean addAuthConfig(String personId, String deviceId, Date startTime, Date endTime) throws Exception {
        ArtemisConfig config = new ArtemisConfig();
        config.setHost(host); // 代理API网关nginx服务器ip端口
        config.setAppKey(appKey);  // 秘钥appkey
        config.setAppSecret(appSecret);// 秘钥appSecret
        final String getCamsApi = ARTEMIS_PATH + "/api/acps/v1/auth_config/add";
        Map<String, Object> paramMap = new HashMap<String, Object>();// post请求Form表单参数

        //配置权限下发参数
        JSONObject personParmJson=new JSONObject();
        List<Object> personIds=new ArrayList<>();
        List<Object> personDatas=new ArrayList<>();
        personIds.add(personId);
        personParmJson.put("indexCodes",personIds);
        personParmJson.put("personDataType","person");
        personDatas.add(personParmJson);
        paramMap.put("personDatas",personDatas);
        //拼接门禁设备参数
        JSONObject resourceInfosParmJson=new JSONObject();
        resourceInfosParmJson.put("resourceIndexCode",deviceId);
        resourceInfosParmJson.put("resourceType","door");
        List<Object> resourceIds=new ArrayList<>();
        resourceIds.add(resourceInfosParmJson);
        paramMap.put("resourceInfos",resourceIds);
        //拼接时间参数
//        String startTimeFomartString=DateUtil.format(startTime, DatePattern.ISO8601_FORMAT);
//        String endTimeFomartString=DateUtil.format(endTime,DatePattern.ISO8601_FORMAT);
//        paramMap.put("startTime", startTimeFomartString);
//        paramMap.put("endTime", endTimeFomartString);
        paramMap.put("startTime","2024-09-03T17:30:08+08:00");
        paramMap.put("endTime","2025-12-30T17:30:08+08:00");
        String body = JSON.toJSON(paramMap).toString();
        Map<String, String> path = new HashMap<String, String>(2) {
            {
                put("https://", getCamsApi);
            }
        };
        Map<String, String> head = new HashMap<String, String>(2) {
            {
                put("tagId", tagId);
            }
        };
        String resultDataString= ArtemisHttpUtil.doPostStringArtemis(config,path, body, null, null, "application/json",head);
        JSONObject resultObject = JSON.parseObject(resultDataString);
        JSONObject devicesObject=(JSONObject) resultObject.get("data");
        String taskIdString=String.valueOf(devicesObject.get("taskId"));
        boolean result=false;
        if(StringUtils.isNotEmpty(taskIdString)){
            result=true;
        }
        return result;
    }
}
